package com.example.pressabkey;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.KeyCharacterMap;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageButton;
import android.widget.Switch;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity implements View.OnClickListener,
        View.OnKeyListener, View.OnTouchListener {
    ImageButton[] buttons=new ImageButton[2];
    private TextView tv_info,tv_choose;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        buttons[0]=(ImageButton) findViewById(R.id.ib_img1);
        buttons[1]=(ImageButton) findViewById(R.id.ib_img2);
        tv_info=(TextView) findViewById(R.id.tv_info);
        tv_info.setText("请使用键盘中的A、B键控制下方两个按钮");
        tv_choose=(TextView) findViewById(R.id.tb_choose);
        for(ImageButton button:buttons){
            button.setOnClickListener(this);
            button.setOnKeyListener(this);
        }
    }

    @Override
    public void onClick(View view) {
        switch(view.getId()){
            case R.id.ib_img1:
                tv_choose.setText("您点击了按钮A");
                break;
            case R.id.ib_img2:
                tv_choose.setText("您点击了按钮B");
                break;
        }
    }

    @Override
    public boolean onKey(View view, int keyCode, KeyEvent keyEvent) {
       switch(keyCode){
           case KeyEvent.KEYCODE_A:
               buttons[0].performClick();
               buttons[0].requestFocus();
               break;
           case KeyEvent.KEYCODE_B:
               buttons[1].performClick();
               buttons[1].requestFocus();
               break;
       }
        return false;
    }

    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
        switch (view.getId()){
            case R.id.ib_img1:
                if(motionEvent.getAction()==MotionEvent.ACTION_MOVE){  //效果不明显
                    tv_choose.setText("您移动通过了A按钮");
                }
                break;
            case R.id.ib_img2:
                if(motionEvent.getAction()==MotionEvent.ACTION_MOVE){  //效果不明显
                    tv_choose.setText("您移动通过了B按钮");
                }
                break;
        }
        return false;
    }
}
